package io.xccit.train.generator.utils;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Map;

/**
 * @author CH_ywx
 * @version 1.0
 * @create 2024/11/16
 * <p>freemarker工具类</p>
 */
public class FreemakerUtil {

    private static String ftlPath = "train-generator\\src\\main\\java\\io\\xccit\\train\\generator\\ftl\\";

    private static Template template;

    /**
     * 初始化配置
     * @param ftlName 模板名称
     * @throws IOException
     */
    public static void initConfig(String ftlName) throws IOException {
        Configuration configuration = new Configuration(Configuration.VERSION_2_3_31);
        configuration.setDirectoryForTemplateLoading(new File(ftlPath));
        configuration.setObjectWrapper(new DefaultObjectWrapper(Configuration.VERSION_2_3_31));
        template = configuration.getTemplate(ftlName);
    }

    /**
     * 生成文件
     * @param fileName 文件名
     * @param data 模板数据
     */
    public static void generatorFtl(String fileName, Map<String,Object> data) throws IOException, TemplateException {
        FileWriter fileWriter = new FileWriter(fileName);
        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
        template.process(data,bufferedWriter);
        bufferedWriter.flush();
        bufferedWriter.close();
        fileWriter.close();
    }
}
